package com.itheima.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器的使用步骤：
 * 1.定义一个类，实现HandlerInterceptor接口，并重写里面的方法
 * 2.将拦截器类交给IOC容器管理
 * 3.注册拦截器：定义一个配置类，实现一个接口WebMvcConfigurer
 * 4.重写addInterceptors()方法，添加自定义拦截器
 */
@Component
public class DemoInterceptor implements HandlerInterceptor {
    //在执行目标方法之前执行，返回值：如果返回的是true，代表放行；false的话代表不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return true;    //放行
    }

    //在执行目标方法之后执行，前提：preHandle方法返回的是true才会执行该方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    //视图渲染完毕之后执行，postHandle()之后触发
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
